package org.test.java;

import static org.test.java.ShuaTa.httpRequestWithLogFile;
import static org.test.java.ShuaTa.logFile;
import static org.test.java.ShuaTa.print;
import static org.test.java.ShuaTa.sleepTime;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

public class EditMapStage implements Runnable {

	private String _sid;
	Properties props;
	private static String logFile = "EditMapStage.log";

	public EditMapStage(String _sid, Properties props) {
		this._sid = _sid;
		this.props = props;
		if (props.containsKey("editMapStageLogFile")) {
			logFile = props.getProperty("editMapStageLogFile");
		}
		sleepTime = 3600 * 1000;
	}

	@Override
	public void run() {
		int max = 150;
		int current = 0;
		int tili = -1;
		while (true) {
			try {
				while (true) {
					current++;
					if (current > max) {
						current = 0;
						break;
					}
					Map map = httpRequestWithLogFile(_sid, "user.php",
							"GetUserinfo", "", logFile);
					if (getInt(map, "status") != 1) {
						try {
							Thread.sleep(1000 * 60);
						} catch (InterruptedException e) {
							e.printStackTrace();
							log(e.toString());
						}
						continue;
					}
					tili = getInt((Map) map.get("data"), "Energy");
					if (tili < 2) {
						try {
							Thread.sleep(1000 * 60);
						} catch (InterruptedException e) {
							e.printStackTrace();
							log(e.toString());
						}
						continue;
					}
					try {
						Map stages = httpRequestWithLogFile(_sid,
								"mapstage.php", "GetUserMapStages", "", logFile);
						if (getInt(stages, "status") != 1) {
							try {
								Thread.sleep(1000 * 60);
							} catch (InterruptedException e) {
								e.printStackTrace();
								log(e.toString());
							}
							continue;
						}
						Map dataMaps = (Map) stages.get("data");
						if (dataMaps.get(String.valueOf(current)) == null)
							continue;
						if (!"3".equals(((Map) dataMaps.get(String
								.valueOf(current))).get("FinishedStage").toString()))
							continue;
					} catch (Exception e) {
						e.printStackTrace();
					}

					Map result = httpRequestWithLogFile(_sid, "mapstage.php",
							"EditUserMapStages", "MapStageDetailId="
									+ current + "&isManual=0", logFile);
					log(result.toString());
					
					if (getInt(result, "status") != 1) {
						continue;
					}
				}

				Thread.sleep(1000 * 3600 * 5);
			} catch (IOException e) {
				e.printStackTrace();
				log(e.getMessage());
			} catch (InterruptedException e) {
				e.printStackTrace();
				log(e.getMessage());
			}
		}
	}

	private int getInt(Map map, String key) {
		return (Double.valueOf(map.get(key).toString())).intValue();
	}

	private void log(String result) {
		try {
			print(logFile, result);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

}
